package com.gnerv.sylvanas.authentication.security.config.handler;

import com.gnerv.sylvanas.framework.common.model.RestResult;
import com.gnerv.sylvanas.framework.common.model.RestResultCode;
import com.gnerv.sylvanas.framework.core.tools.JsonTools;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author Gnerv LiGen
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter writer = response.getWriter();
        writer.println(JsonTools.toJsonString(RestResult.error(RestResultCode.CODE_200)));
        writer.close();
    }

}
